package com.lsq.baseadmin.common.utils;

import eu.bitwalker.useragentutils.Browser;
import eu.bitwalker.useragentutils.UserAgent;
import org.thymeleaf.util.Validate;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author pc12138
 * @since 2020/10/27 9:43
 */
public class MyUtil {


    /**
     * 获取浏览器信息
     * @param request HttpServletRequest
     * @return 浏览器信息
     */
    public static String getBrowser(HttpServletRequest request){
        UserAgent userAgent = UserAgent.parseUserAgentString(request.getHeader("User-Agent"));
        Browser browser = userAgent.getBrowser();
        return browser.getName();
    }

    /**
     * 判断该对象全部字段是null: 返回ture表示所有属性为null  则返回false
     * <p>
     * 注： 对象下有实例化的属性ID 名必须为 serialVersionUID，此属性不判断。
     */
    public static boolean allFieldsIsNull(Object obj) {
        // 得到类对象
        Class stuCla = obj.getClass();
        Field[] fs = getAllFields(stuCla);
        //Field[] fs = stuCla.getDeclaredFields();//得到属性集合
        boolean flag = true;
        try {
            //遍历属性
            for (Field f : fs) {
                // 设置属性是可以访问的(私有的也可以)
                f.setAccessible(true);
                if ("serialVersionUID".equals(f.getName())) {
                    continue;
                }
                // 得到此属性的值
                Object val = f.get(obj);
                //只要有1个属性不为空,那么就不是所有的属性值都为空
                if (val != null) {
                    flag = false;
                    break;
                }
            }
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
        return flag;
    }

    private static Field[] getAllFields(final Class<?> cls) {
        final List<Field> allFieldsList = getAllFieldsList(cls);
        return allFieldsList.toArray(new Field[allFieldsList.size()]);
    }
    private static List<Field> getAllFieldsList(final Class<?> cls) {
        Validate.isTrue(cls != null, "The class must not be null");
        final List<Field> allFields = new ArrayList<Field>();
        Class<?> currentClass = cls;
        while (currentClass != null) {
            final Field[] declaredFields = currentClass.getDeclaredFields();
            Collections.addAll(allFields, declaredFields);
            currentClass = currentClass.getSuperclass();
        }
        return allFields;
    }
}
